package com.xiaoq.order.endpoint;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xiaoq.BaseEndpoint2B;
import com.xiaoq.apis.interpreter.IInterpreterApi;
import com.xiaoq.apis.interpreter.InterCalendar4OrderVo;
import com.xiaoq.apis.interpreter.Interpreter4OrderVo;
import com.xiaoq.apis.user.IUserApi;
import com.xiaoq.apis.user.UserInfo4InterVo;
import com.xiaoq.apis.user.UserInfo4OrderTourVo;
import com.xiaoq.apis.user.UserInfo4UserCouponVo;
import com.xiaoq.coms.GenericDataResponse;
import com.xiaoq.coms.GenericListResponse;
import com.xiaoq.coms.GenericResponse;
import com.xiaoq.coms.util.ConstantUtil;
import com.xiaoq.coms.util.MathUtil;
import com.xiaoq.distribution.entity.TicketOrderItemEntity;
import com.xiaoq.distribution.service.ITicketOrderItemService;
import com.xiaoq.order.entity.OrderTourPipe;
import com.xiaoq.order.entity.PayState;
import com.xiaoq.order.entity.ShopOrderEntity;
import com.xiaoq.order.entity.ShoppingItem;
import com.xiaoq.order.service.IShopOrderService;
import com.xiaoq.order.vo.*;
import com.xiaoq.vo.PagingVo;
import io.swagger.annotations.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/api/v1/mgr_orders")
@Api(tags = "B 端订单查询相关接口")
class ShopOrderEndpoint2B extends BaseEndpoint2B{

    private static final class ShopOrderResponse extends GenericListResponse<ShopOrderVo> {}
    private static final class OrderStatisResponse extends GenericDataResponse<OrderStatis> {}
    private static final class OrderTourPipeResponse extends GenericListResponse<OrderTourPipe> {}
    private static final class SettleTicketCodeResponse extends GenericDataResponse<SettleTicketCodeVo> {}

    private static final class SettleTicketCodeListResponse extends GenericListResponse<SettleTicketCodeVo> {}


    @Autowired
    private IShopOrderService shopOrderService;

    @Reference(interfaceClass=IInterpreterApi.class, check=false, version="1.0.0")
    private IInterpreterApi interpreterApi;

    @Reference(interfaceClass=IUserApi.class, check=false, version="1.0.0")
    private IUserApi userDubboApi;

    @Autowired
    private ITicketOrderItemService ticketOrderItemService;

    //获取用户的各种订单列表
    @ApiOperation(value="查询用户的订单列表", notes="查询用户的订单列表")
    @ApiResponses({
            @ApiResponse(code = 200, response = ShopOrderResponse.class, message = "待支付：paystate(0),orderstate(0)\n" +
                    "已支付（待使用）：paystate(1),orderstate(4)\n" +
                    "已关闭(取消)：paystate(0)，orderstate(9)\n" +
                    "已完成：paystate(1)，orderstate(5)\n" +
                    "已评价：paystate(1)，orderstate(6)")
    })
    @GetMapping(value = "", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<?> findShopOrders(
            HttpServletRequest request,
            @ApiParam(required = true, name = "orderState", value = "订单状态:99,所有;0,待支付;4,待使用;5,已完成;6,已评价;9,已关闭")
            @RequestParam Integer orderState,
            @ApiParam(required = false, name = "payState", value = "支付状态:0,待支付;1,已支付;")
            @RequestParam(required = false) Integer payState,
            @ApiParam(required = false, name = "startOrderTime", value = "下单开始时间(yyyy-MM-dd HH:mm:ss)")
            @RequestParam(required = false)  String startOrderTime,
            @ApiParam(required = false, name = "endOrderTime", value = "下单结束时间 (yyyy-MM-dd HH:mm:ss)")
            @RequestParam(required = false)  String endOrderTime,
            @ApiParam(required = false, name = "orderId", value = "订单ID")
            @RequestParam(required = false) String orderId,
            @ApiParam(required = false, name = "payType", value = "支付方式(1:微信支付,2:支付宝支付)")
            @RequestParam(required = false) Integer payType,
            @ApiParam(required = false, name = "orderType", value = "订单类型:1,讲解员订单,0:购票订单")
            @RequestParam(required = false) Integer orderType,
            @ApiParam(value="pn", required=false) @RequestParam(required = false, defaultValue = "1") int pn,
            @ApiParam(value="ps", required=false) @RequestParam(required = false, defaultValue = "10") int ps
            /*,
            @ApiParam(required = true, name = "pagingTimeOfPreRecord", value = "分页用的时间戳")
            @RequestParam Long pagingTimeOfPreRecord,
            @ApiParam(required = true, name = "pageSize", value = "每页数据条数")
            @RequestParam int pageSize*/) {

        PagingVo pagingVo = new PagingVo(pn, ps);

        String shopId = getShopId();
        if(StringUtils.isEmpty(shopId)){
            return GenericResponse.ng("没取到此用户的所属店信息");
        }
        DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
        Long startOrderTimeLong = null;
        Long endOrderTimeLong = null;
        if(StringUtils.isNotBlank(startOrderTime)){
            try {
                startOrderTimeLong = DateTime.parse(startOrderTime, format).getMillis();
            }catch (Exception e){
                return GenericResponse.ng("预订时间格式不对");
            }
        }
        if(StringUtils.isNotBlank(endOrderTime)){
            try {
                endOrderTimeLong = DateTime.parse(endOrderTime, format).getMillis();
            }catch (Exception e){
                return GenericResponse.ng("预订结束格式不对");
            }
        }

        if(orderState!=null && orderState==99){
            orderState = null;
        }

        OrderQueryVo orderQueryVo = new OrderQueryVo();
        orderQueryVo.setCreateTime(startOrderTimeLong);
        orderQueryVo.setEndOrderTime(endOrderTimeLong);
        orderQueryVo.setInterpreterId(null);
        orderQueryVo.setPayState(payState);
        orderQueryVo.setOrderState(orderState);
        orderQueryVo.setShopId(shopId);
        orderQueryVo.setShopOrderId(orderId);
        orderQueryVo.setOrderType(orderType);
        orderQueryVo.setPayType(payType);
        orderQueryVo.setPayState(payState);

        List<ShopOrderEntity> orderEntityList = shopOrderService.getShopAllOrders(orderQueryVo, pagingVo);
        long totalCount = shopOrderService.getShopAllOrdersCount(orderQueryVo, pagingVo);
        List<ShopOrderVo> shopOrderVoList = new ArrayList<>();

        Map<String, ShopOrderEntity> orderId2Order = new LinkedHashMap<>();
        if(CollectionUtils.isEmpty(orderEntityList)){
            return ShopOrderResponse.listAndCount(shopOrderVoList, totalCount);
        }
        List<String> orderIdList = new ArrayList<>();
        for(ShopOrderEntity shopOrder : orderEntityList){
            if(StringUtils.isNotBlank(shopOrder.getInterpreterId())){
                orderIdList.add(shopOrder.getShopOrderId());
            }
            orderId2Order.put(shopOrder.getShopOrderId(), shopOrder);
        }

        List<InterCalendar4OrderVo> interCalendarList = null;
        if(CollectionUtils.isNotEmpty(orderIdList)){
            try {
                interCalendarList = interpreterApi.getInterCalendarList(orderIdList);
            }catch (Exception e){
                logger.error(e.getMessage(), e);
            }
        }

        Map<String, InterCalendar4OrderVo> orderId2InterCalendarMap = null;
        if(CollectionUtils.isNotEmpty(interCalendarList)){
            orderId2InterCalendarMap = interCalendarList.stream().collect(Collectors.toMap(InterCalendar4OrderVo::getOrderId, calendarVo -> calendarVo));
        }
        if(orderId2InterCalendarMap == null){
            orderId2InterCalendarMap = new HashMap<>();
        }

        ShopOrderVo shopOrderVo;
        for(ShopOrderEntity shopOrder : orderEntityList){
            String shopOrderId = shopOrder.getShopOrderId();
            shopOrderVo = new ShopOrderVo();
            BeanUtils.copyProperties(shopOrder, shopOrderVo);
            shopOrderVo.setTotalAmount(MathUtil.decimal2Digits(shopOrderVo.getTotalAmount(), 2));
            if(orderId2InterCalendarMap.containsKey(shopOrderId)){
                shopOrderVo.setCalendarVo(orderId2InterCalendarMap.get(shopOrderId));
            }

            shopOrderVoList.add(shopOrderVo);
        }

        return ShopOrderResponse.listAndCount(shopOrderVoList, totalCount);
    }


    @ApiOperation(value="订单数据统计", notes="订单数据统计")
    @ApiResponses({
            @ApiResponse(code = 200, response = OrderStatisResponse.class, message = "订单数据统计")
    })
    @GetMapping(value = "/orderstatis", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<?> orderstatis() {

        String shopId = getShopId();
        if(StringUtils.isEmpty(shopId)){
            return GenericResponse.ng("没取到此用户的所属店信息");
        }

        DateTime currentDate = new DateTime();
        DateTime yestodayEnd = new DateTime(currentDate.getYear(),
                currentDate.getMonthOfYear(),
                currentDate.getDayOfMonth(),
                0,
                0);
        DateTime yestodayBegin = yestodayEnd.minusDays(1);

        OrderQueryVo orderQueryVo = new OrderQueryVo();
        orderQueryVo.setCreateTime(yestodayBegin.getMillis());
        orderQueryVo.setEndOrderTime(yestodayEnd.getMillis());
        orderQueryVo.setPayState(PayState.PAID.value());
        orderQueryVo.setShopId(shopId);
        //暂不考虑退款  昨天订单相关信息
        List<ShopOrderEntity> yesOrderList = shopOrderService.getShopAllOrders(orderQueryVo, null);
        double yesTotalMoney = 0D;
        int yesOrderCount = 0;
        int todayOrderCount = 0;
        double totalMoney = 0D;

        if(CollectionUtils.isNotEmpty(yesOrderList)){
            for(ShopOrderEntity orderEntity : yesOrderList){
                if(orderEntity.getRealPayMoney() != null){
                    yesTotalMoney += orderEntity.getRealPayMoney();
                }
                yesOrderCount++;
            }
        }

        //今日订单相关信息
        OrderQueryVo todayOrderQueryVo = new OrderQueryVo();
        todayOrderQueryVo.setCreateTime(yestodayEnd.getMillis());
        todayOrderQueryVo.setEndOrderTime(yestodayEnd.plusDays(1).getMillis());
        todayOrderQueryVo.setPayState(PayState.PAID.value());
        todayOrderQueryVo.setShopId(shopId);

        List<ShopOrderEntity> todayOrderList = shopOrderService.getShopAllOrders(todayOrderQueryVo, null);
        todayOrderCount = todayOrderList==null?0:todayOrderList.size();

        //TODO 待优化 mongo Aggregation 操作不熟悉, (暂时做循环取总的金额)
        OrderQueryVo todayMoneyQueryVo = new OrderQueryVo();
        todayMoneyQueryVo.setShopId(shopId);
        List<ShopOrderEntity> totalMoneyOrderList = shopOrderService.getShopAllOrders(todayMoneyQueryVo, null);
        if(CollectionUtils.isNotEmpty(totalMoneyOrderList)){
            for(ShopOrderEntity orderEntity : totalMoneyOrderList){
                if(orderEntity.getRealPayMoney() != null){
                    totalMoney += orderEntity.getRealPayMoney();
                }
            }
        }

        OrderStatis orderStatis = new OrderStatis();
        orderStatis.setYesterdayOrderCount(yesOrderCount);
        orderStatis.setYesterdayOrderTotalMoney(MathUtil.decimal2Digits(yesTotalMoney, 2));
        orderStatis.setTodayOrderCount(todayOrderCount);
        orderStatis.setTotalMoney(MathUtil.decimal2Digits(totalMoney, 2));

        return OrderStatisResponse.okWithData(orderStatis);
    }

    @ApiOperation(value="讲解员结束服务", notes="讲解员结束服务")
    @ApiResponses({
            @ApiResponse(code = 200, response = GenericResponse.class, message = "讲解员结束服务")
    })
    @PutMapping(value = "/{shopOrderId}/orderstate/endservice", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<?> endService(
            HttpServletRequest request,
            @ApiParam(required = true, name = "shopOrderId", value = "订单id")
            @PathVariable String shopOrderId,
            @ApiParam(required = true, name = "userId", value = "下单人id")
            @RequestParam String userId) {

        UserInfo4UserCouponVo userInfo4UserCouponVo = userDubboApi.getUserInfoById(userId);
        if(userInfo4UserCouponVo==null || StringUtils.isBlank(userInfo4UserCouponVo.getId())){
            return GenericResponse.ng("此用户未登录或不存在");
        }
        Interpreter4OrderVo interpreter4OrderVo = interpreterApi.getInterByUserId(userId);

        if(interpreter4OrderVo == null){
            return GenericResponse.ng("userId为【"+userId+"】, 对应的讲解员不存在");
        }

        ShopOrderEntity shopOrderEntity = shopOrderService.getShopOrderByOrderId(shopOrderId);
        if(shopOrderEntity == null
                || !StringUtils.equals(shopOrderEntity.getInterpreterId(), interpreter4OrderVo.getId())){
            return GenericResponse.ng("此订单不存在或是别人的订单");
        }
        String interId = shopOrderEntity.getInterpreterId();
        ShopOrderEntity newShopOrderEntity = new ShopOrderEntity();
        newShopOrderEntity.setShopOrderId(shopOrderId);
        newShopOrderEntity.setOrderState(ConstantUtil.INTERPRETER_CALENDAR_STATUS_COMPLETE);
        boolean updateOrderFlag = shopOrderService.updateShopOrderByOrderId(newShopOrderEntity);

        try {
            boolean successFlag = interpreterApi.updateInter2CanAppoint(interId, shopOrderEntity.getShopId());
            if(!successFlag){
                logger.error("解锁讲解员至可预约状态失败。interId: " + interId + ",orderId: " + shopOrderId);
            }
        }catch (Exception e){
            logger.error("解锁讲解员至可预约状态失败。interId: " + interId + ",orderId: " + shopOrderId + "," + e.getMessage(), e);
        }

        try {
            boolean successFlag = interpreterApi.updateInterCalendarStatus(shopOrderId, ConstantUtil.INTERPRETER_CALENDAR_STATUS_COMPLETE);
            if(!successFlag){
                logger.error("解锁讲解员日历至完成状态失败。interId: " + interId + ",orderId: " + shopOrderId);
            }
        }catch (Exception e){
            logger.error("解锁讲解员日历至完成状态失败。interId: " + interId + ",orderId: " + shopOrderId + "," + e.getMessage(), e);
        }

        if(updateOrderFlag){
            return GenericResponse.ok();
        }
        logger.error("结束服务订单失败,订单ID: " + shopOrderId + ", interId: " + userId);
        return GenericResponse.ng("结束服务订单失败");
    }


    //获取用户的各种订单列表
    @ApiOperation(value="游客一览 数据统计", notes="游客一览 数据统计")
    @ApiResponses({
            @ApiResponse(code = 200, response = OrderTourPipeResponse.class, message = "游客一览 数据统计")
    })
    @GetMapping(value = "/tours", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<?> touristList(
            HttpServletRequest request,
            @ApiParam(required = false, name = "userFrom", value = "用户来自哪里")
            @RequestParam(required = false) String userFrom,

            @ApiParam(required = false, name = "mobile", value = "用户电话")
            @RequestParam(required = false)  String mobile,

            @ApiParam(required = false, name = "orderCount", value = "消费次数")
            @RequestParam(required = false)  Integer orderCount,

            @ApiParam(required = false, name = "consumeMinMoney", value = "消费最小金额")
            @RequestParam(required = false) Integer consumeMinMoney,

            @ApiParam(required = false, name = "consumeMaxMoney", value = "消费最大金额")
            @RequestParam(required = false) Integer consumeMaxMoney,

            @ApiParam(value="pn", required=false) @RequestParam(required = false, defaultValue = "1") int pn,
            @ApiParam(value="ps", required=false) @RequestParam(required = false, defaultValue = "10") int ps) {

        PagingVo pagingVo = new PagingVo(pn, ps);

        String shopId = getShopId();
        if(StringUtils.isEmpty(shopId)){
            return GenericResponse.ng("没取到此用户的所属店信息");
        }

        String phoneUserId = "";  //要查询的用户ID
        if(StringUtils.isNotBlank(mobile)){
            try {
                UserInfo4InterVo userInfo4InterVo = userDubboApi.getUserByMobile(mobile.trim());
                if(userInfo4InterVo != null){
                    phoneUserId = userInfo4InterVo.getId();
                }else {
                    return OrderTourPipeResponse.listAndCount(new ArrayList<>(), 0);
                }
            }catch (Exception e){

            }
        }

        OrderTourPipeQueryVo pipeQueryVo = new OrderTourPipeQueryVo();
        pipeQueryVo.setShopId(shopId);
        pipeQueryVo.setUserId(phoneUserId);
        pipeQueryVo.setUserFrom(userFrom);
        pipeQueryVo.setConsumeMaxMoney(consumeMaxMoney);
        pipeQueryVo.setConsumeMinMoney(consumeMinMoney);
        pipeQueryVo.setOrderCount(orderCount);
        pipeQueryVo.setPayState(PayState.PAID.value());

        List<OrderTourPipe> list = shopOrderService.getShopAllOrders4Tour(pipeQueryVo, pagingVo);
        long  totalCount = shopOrderService.getShopAllOrders4TourCount(pipeQueryVo);

        List<String> userIdList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(list)){
            for(OrderTourPipe orderTourPipe : list){
                userIdList.add(orderTourPipe.getUserId());
            }
        }

        List<UserInfo4OrderTourVo> userInfo4OrderTourVoList = null;
        try {
            userInfo4OrderTourVoList = userDubboApi.getUserInfo4OrderTourByUserIds(userIdList);
        }catch (Exception e){
            logger.error("获取用户信息失败, {}", e.getMessage());
        }

        if(CollectionUtils.isNotEmpty(userInfo4OrderTourVoList)){
            Map<String, UserInfo4OrderTourVo> userId2UserInfoMap = new HashMap<>();
            for(UserInfo4OrderTourVo userInfo4OrderTourVo : userInfo4OrderTourVoList){
                userId2UserInfoMap.put(userInfo4OrderTourVo.getId(), userInfo4OrderTourVo);
            }

            for(OrderTourPipe orderTourPipe : list){
                UserInfo4OrderTourVo userInfo4OrderTourVo = userId2UserInfoMap.get(orderTourPipe.getUserId());
                orderTourPipe.setVip(0);
                if(userInfo4OrderTourVo != null){
                    orderTourPipe.setNickName(userInfo4OrderTourVo.getNickName());
                    orderTourPipe.setWxNickName(userInfo4OrderTourVo.getThirdNickName());
                    orderTourPipe.setUserPhone(userInfo4OrderTourVo.getMobile());
                }

                //保留2位小数
                orderTourPipe.setTotalAmount(MathUtil.decimal2Digits(orderTourPipe.getTotalAmount(), 2));
            }
        }

        return GenericListResponse.listAndCount(list, totalCount);
    }

    //电子票查询
    @ApiOperation(value="电子码号查询", notes="电子码号查询")
    @ApiResponses({
            @ApiResponse(code = 200, response = SettleTicketCodeResponse.class, message = "电子码号查询")
    })
    @GetMapping(value = "/ticketcode/{ticketCode}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<?> ticketCodeQuery(
            HttpServletRequest request,
            @ApiParam(required = true, name = "ticketCode", value = "电子码号")
            @PathVariable String ticketCode) {

        TicketOrderItemEntity ticketOrderItemEntity = ticketOrderItemService.getByTicketCode(ticketCode);

        if(ticketOrderItemEntity == null){
            return GenericResponse.ng("电子码号不存在");
        }

        String shopOrderId = ticketOrderItemEntity.getShopOrderId();
        ShopOrderEntity shopOrderEntity = shopOrderService.getShopOrderByOrderId(shopOrderId);
        if(shopOrderEntity == null){
            return GenericResponse.ng("不存在此订单");
        }

        List<ShoppingItem> itemList = shopOrderEntity.getShoppingItems();

        SettleTicketCodeVo settleTicketCodeVo = new SettleTicketCodeVo();
        if(ticketOrderItemEntity.getUseTime() != null){
            settleTicketCodeVo.setUseTime(ticketOrderItemEntity.getUseTime());
            settleTicketCodeVo.setRemainUseCount(0);
        }else {
            settleTicketCodeVo.setRemainUseCount(1);
        }

        if(CollectionUtils.isNotEmpty(itemList)){
            settleTicketCodeVo.setTravelDate(itemList.get(0).getTravelDate());
        }
        settleTicketCodeVo.setShopOrderId(shopOrderId);
        settleTicketCodeVo.setTicketCode(ticketCode);
        settleTicketCodeVo.setTourName(shopOrderEntity.getUserRealName());
        settleTicketCodeVo.setSettleUserName(ticketOrderItemEntity.getSettleUserId());

        return SettleTicketCodeResponse.okWithData(settleTicketCodeVo);
    }


    //电子票核销
    @ApiOperation(value="电子码号核销", notes="电子码号核销")
    @ApiResponses({
            @ApiResponse(code = 200, response = GenericResponse.class, message = "电子码号核销")
    })
    @PostMapping(value = "/ticketcode/{ticketCode}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<?> ticketCode4Settle(
            HttpServletRequest request,
            @ApiParam(required = true, name = "ticketCode", value = "电子码号")
            @PathVariable String ticketCode) {

        TicketOrderItemEntity ticketOrderItemEntity = ticketOrderItemService.getByTicketCode(ticketCode);

        if(ticketOrderItemEntity == null){
            return GenericResponse.ng("电子码号不存在");
        }

        String shopOrderId = ticketOrderItemEntity.getShopOrderId();
        ShopOrderEntity shopOrderEntity = shopOrderService.getShopOrderByOrderId(shopOrderId);
        if(shopOrderEntity == null){
            return GenericResponse.ng("不存在此订单");
        }


        if(shopOrderEntity.getPayState() == null || shopOrderEntity.getPayState() != PayState.PAID.value()){
            return GenericResponse.ng("该订单暂未支付");
        }

        List<ShoppingItem> itemList = shopOrderEntity.getShoppingItems();

        if(ticketOrderItemEntity.getUseTime() != null){
            return GenericResponse.ng("此电子票码已核销");
        }

        //查找已结算的票的数量，与订单的数量是否相等，相等则更新订单的状态为已使用
        long ticketCount = 0L;
        if(CollectionUtils.isNotEmpty(itemList)){
            ticketCount = itemList.get(0).getNumber();
        }

        long useTicketCount = ticketOrderItemService.getUseOrderItemCountByOrderId(shopOrderId);

        //更新订单项状态
        TicketOrderItemEntity updateTicketOrder = new TicketOrderItemEntity();
        updateTicketOrder.setId(ticketOrderItemEntity.getId());
        updateTicketOrder.setUseTime(System.currentTimeMillis());
        updateTicketOrder.setOrderState(ConstantUtil.ORDER_TICKET_STATUS_COMPLETE);
        updateTicketOrder.setSettleUserId(getMgrId());
        
        ticketOrderItemService.updateById(updateTicketOrder);

        if((useTicketCount + 1) == ticketCount){ //由于可能存在不一致的情况
            //更新订单状态
            ShopOrderEntity updateShopOrder = new ShopOrderEntity();
            updateShopOrder.setId(shopOrderEntity.getId());
            updateShopOrder.setShopOrderId(shopOrderId);
            updateShopOrder.setOrderState(ConstantUtil.ORDER_TICKET_STATUS_COMPLETE);
            shopOrderService.updateShopOrderByOrderId(updateShopOrder);
        }

        return GenericResponse.ok();
    }


    @ApiOperation(value="电子码号核销列表", notes="电子码号核销列表")
    @ApiResponses({
            @ApiResponse(code = 200, response = SettleTicketCodeListResponse.class, message = "电子码号核销列表")
    })
    @GetMapping(value = "/ticketcodesettle", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseEntity<?> ticketCodesettleList(
            HttpServletRequest request,
            @ApiParam(required = false, name = "settleStartTime", value = "核销日期开始时间")
            @RequestParam(required = false) Long settleStartTime,

            @ApiParam(required = false, name = "settleEndTime", value = "核销日期结束时间")
            @RequestParam(required = false) Long settleEndTime,

            @ApiParam(required = false, name = "orderIdOrItemIdOrTicketCode", value = "订单号/订单明细编号/电子码")
            @RequestParam(required = false) String orderIdOrItemIdOrTicketCode,

            @ApiParam(value="pn", required=false) @RequestParam(required = false, defaultValue = "1") int pn,
            @ApiParam(value="ps", required=false) @RequestParam(required = false, defaultValue = "10") int ps) {

        PagingVo pagingVo = new PagingVo(pn, ps);

        String shopId = getShopId();
        List<TicketOrderItemEntity> ticketOrderItemList = ticketOrderItemService.getList4SettleRecord(shopId, orderIdOrItemIdOrTicketCode, settleStartTime, settleEndTime, pagingVo);
        long count = ticketOrderItemService.getCount4SettleRecord(shopId, orderIdOrItemIdOrTicketCode, settleStartTime, settleEndTime);

        List<SettleTicketCodeVo> settleTicketCodeList = new ArrayList<>();
        SettleTicketCodeVo settleTicketCodeVo;
        if(CollectionUtils.isNotEmpty(ticketOrderItemList)){
            for (TicketOrderItemEntity ticketOrderItemEntity : ticketOrderItemList){
                settleTicketCodeVo = new SettleTicketCodeVo();
                BeanUtils.copyProperties(ticketOrderItemEntity, settleTicketCodeVo);

                settleTicketCodeVo.setSettleUserName(ticketOrderItemEntity.getSettleUserId());
                settleTicketCodeList.add(settleTicketCodeVo);
            }
        }

        return SettleTicketCodeListResponse.listAndCount(settleTicketCodeList, count);
    }



}

